let express = require("express");
const fs = require('fs');
const path = require("path");
let ejs = require("ejs");
let app = express();
let svgCaptcha = require("svg-captcha");
let cookie = require("cookie-parser");
let persons = fs.readFileSync(__dirname + "/persons.json")
persons = JSON.parse(persons)
app.use(cookie())
//解析表单提交的数据
app.use(express.urlencoded({
    extended: false
}));

app.set("view engine", "html"); //启用的模板引擎为html
app.set("views", __dirname + "/view"); //加载视图文件目录地址
app.engine("html", ejs.__express); //识别网页文件后缀名html，保留ejs功能


// 加载静态资源
app.use(express.static(__dirname + "/static"));


//规划路由生成验证码
app.get("/svgcode", (req, res) => {
    let Captcha = svgCaptcha.create();
    //使用cookie存储验证码的值
    res.cookie("code", Captcha.text);
    res.type("svg"); //使用svg格式生成图片
    res.send(Captcha.data); //将验证码发送给前端

})

app.get("/login", (req, res) => {
    res.render("login.html");
})


app.post("/login", (req, res) => {
    console.log(req.body.username,req.body.password,(req.cookies.code).toUpperCase(),(req.body.code).toUpperCase());
    if ((req.cookies.code).toUpperCase()==(req.body.code).toUpperCase()) {
        persons.find(v => v.username == req.body.username && v.password == req.body.password)?res.send("登录成功"):res.send("用户名密码错误")
    }else{
        res.send("验证码错误")
    }
   
})

app.get("/reg", (req, res) => {
    res.render("register.html");
})

app.post('/reg', (req, res) => {
    let onoff = per.find(val => val.username == req.body.username)
    if (onoff) {
        res.send("用户名已经被占用")
    } else {
        res.send("注册成功")
        per.push({
            "username": req.body.username,
            "password": req.body.password
        })
        fs.writeFileSync(__dirname + '/persons.json', JSON.stringify(per), { flag: "w" })
    }
})


app.listen(4000, "127.0.0.1", (req, res) => {
    console.log("启动服务")
})